import React, { useRef } from 'react'
import { addBannerImg } from '../../api/banner.js'
import { message } from 'antd'

const Add = () => {
    const linkRef = useRef()
    const altRef = useRef()
    const fileRef = useRef()
    const imgRef = useRef()

    const fileReady = () => {
        const file = fileRef.current.files[0]
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function () {
            imgRef.current.src = this.result
        }
    }
    const submitBannerImg = () => {
        const params = {
            link: linkRef.current.value,
            alt: altRef.current.value,
            img: imgRef.current.src
        }
        addBannerImg(params).then( res => {
            message.success({
                content: '添加轮播图成功！',
                className: 'custom-class',
                style: {
                    marginTop: '20vh'
                }
            });
            window.location.href = '/#/banner/list'
        })
    }
    return (
        <>
            <input type="text" ref={linkRef} name="link" placeholder="链接" />
            <input type="text" ref={altRef} name="alt" placeholder="提示" />
            <input type="file" ref={fileRef} onChange={fileReady} name="file" />
            <img src="" ref={imgRef} alt=""/>
            <button style={{width: '150px'}} onClick={submitBannerImg}>添加轮播图</button>
        </>
    )
}

export default Add